<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form style="height: 97%;">
                    <div class="formSolution">
                        <!--按钮 -->
                        <div>
                            <a-form-item :labelCol1="6" :wrapperCol1="18" :label="i18n('list.mode','模式')">
                                <a-radio-group v-model="mode" @change="change">
                                    <a-radio value="easy">
                                        {{ i18n('list.easy', '简易模式') }}
                                    </a-radio>
                                    <a-radio value="hard">
                                        {{ i18n('list.hard', '高级模式') }}
                                    </a-radio>
                                </a-radio-group>
                            </a-form-item>
                        </div>
                        <!--内容-->
                        <div class="formSolution-center" :class="[mode=='easy'?'formSolution-center-flex':'']">
                            <div v-if="mode=='easy'" class="FormSolutionDefMappingConfig-easy">
                                <rx-condition-group ref="easyCondition" :ruleData="easyCondition"
                                                    :defaultRule="defaultRule" :level="2" :allowEmpty="true">
                                    <template slot="conditionDiv" slot-scope="{rule,setValid}">
                                        <div style="display:flex;">
                                            <div class="findSelectBox">
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18nSol('field','字段')"
                                                          style="width: 100%"
                                                          v-model="rule.formField"
                                                          allowClear
                                                          @change="formFieldChange(rule.formField,rule,setValid)"
                                                          :options="formFields"/>
                                            </div>
                                            <div class="findSelectBox" v-if="rule.isSingle===0">
                                                <a-select v-model="rule.fieldValue">
                                                    <a-select-option value="value">{{$comi18('listDef.val', '值')}}</a-select-option>
                                                    <a-select-option value="label">{{$ti18('rxForm.name', '名称')}}</a-select-option>
                                                </a-select>
                                            </div>
                                            <div class="findSelectBox">
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18nSol('comparative','比较符')"
                                                          v-if="rule.dataType=='number' || rule.dataType=='int'"
                                                          v-model="rule.op"
                                                          :options="numOptions"/>
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18nSol('comparative','比较符')"
                                                          v-else-if="rule.dataType=='date'" v-model="rule.op"
                                                          :options="dateOptions"/>
                                                <a-select :getPopupContainer="p=>p.parentNode" v-else
                                                          :placeholder="i18nSol('comparative','比较符')"
                                                          v-model="rule.op"
                                                          :options="strOptions"/>
                                            </div>
                                            <div class="findInputBox" v-if="rule.op!='ISNULL' && rule.op!='NOTNULL'">
                                                <a-input-number v-if="rule.dataType=='number' || rule.dataType=='int'"
                                                                :min="0"
                                                                v-model="rule.conditionConfig"
                                                                :placeholder="i18nSol('condition','条件')"/>
                                                <a-date-picker v-else-if="rule.dataType=='date'"
                                                               format="YYYY-MM-DD"
                                                               value-format="YYYY-MM-DD"
                                                               v-model="rule.conditionConfig"
                                                               :getCalendarContainer="p=>p.parentNode"/>
                                                <a-input v-else
                                                         v-model="rule.conditionConfig"
                                                         :placeholder="i18nSol('condition','条件')"/>

                                            </div>
                                        </div>
                                    </template>
                                </rx-condition-group>
                            </div>
                            <div v-if="mode=='hard'" class="rx-monaco-editor-center" style="margin-right: 20px">
                                <a-alert
                                    :message="i18nSol('buttonUse', '满足以下条件，可以显示按钮')"
                                    :description="i18nSol('enterJava', '在下面代码编辑器输入JAVA代码作为按钮前置条件，可以点击左侧字段快捷插入')"
                                    type="info"
                                    show-icon
                                />
                                <rx-monaco-editor style="margin-top: 10px"
                                                  :key="mode"
                                                  ref="javaCode"
                                                  v-model="javaCode"
                                                  language="java">
                                    <template v-slot:monacoeditor>
                                        <div style="display: flex;align-items: center">
                                            <div class="form-tree-certen">
                                                <a-button style="margin-right: 8px;width: 170px">
                                                    {{ i18n('insertField', '插入表单字段') }}
                                                    <a-icon type="down"/>
                                                </a-button>
                                                <div class="form-tree">
                                                    <a-input-search v-model="search"
                                                                    style="margin-bottom: 8px;width: 150px;margin-left: 10px"
                                                                    :placeholder="i18n('enterField', '输入搜索字段')"
                                                                    @pressEnter="pressEnter(search)"
                                                                    @search="pressEnter(search)"
                                                                    allowClear
                                                                    @change="pressEnter(search)"/>
                                                    <a-tree
                                                        :multiple="false"
                                                        :show-icon="false"
                                                        :treeData="boData"
                                                        @select="selectBoNode"
                                                    ></a-tree>
                                                </div>
                                            </div>
                                            <a-dropdown>
                                                <a-menu slot="overlay">
                                                    <a-menu-item @click="selectBoNodeList(item)"
                                                                 v-for="item in boDataList" :key="item.key">
                                                        {{ item.title }}
                                                    </a-menu-item>
                                                </a-menu>
                                                <a-button style="margin-right: 8px">{{ i18n('insertContext', '插入上下文') }}
                                                    <a-icon type="down"/>
                                                </a-button>
                                            </a-dropdown>
                                            <a-button icon="edit" @click="showScriptDialog()">
                                                {{ i18n('list.quickScript', '快速脚本') }}
                                            </a-button>
                                        </div>
                                    </template>
                                </rx-monaco-editor>
                            </div>
                            <div class="rx-monaco-editor-center">
                                <a-alert
                                    :message="i18n('promptMsg', '不满足按钮前置条件时的提示信息')"
                                    :description="i18n('javaCode', '在下面代码编辑器输入JAVA代码作为不满足前置条件的错误提示')"
                                    type="info"
                                    show-icon
                                />
                                <rx-monaco-editor ref="validMsg"
                                                  :key="mode"
                                                  style="margin-top: 10px"
                                                  v-model="validMsg"
                                                  language="java">
                                </rx-monaco-editor>
                            </div>
                        </div>
                    </div>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import {RxDialog, RxLayout, Util, RxGrid, RxMonacoEditor, Dialog,RxConditionGroup} from "@lowcode/jpaas-common-lib";
import FormBoDefApi from "@/api/form/bo/formBoDef";

export default {
    name: "FormSolutionButtonPreMappingConfig",
    components: {
        RxDialog,
        RxLayout,
        RxGrid,
        RxMonacoEditor,
        RxConditionGroup
    },
    props: ["layerid", "destroy", "config", "boDefId"],
    data() {
        return {
            mode: "easy",
            easyCondition:{
                condition:"AND",
                rules:[],
            },
            defaultRule:{
                formField:undefined,
                op:"EQ",
                conditionConfig:"",
                dataType:"",
                isSingle:"",
                valid:false,
                validMessage:this.i18nSol('fieldNoEmpty','字段不能为空')
            },
            formFields: [],
            boData: [],
            boDataInit: [],
            boDataList: [{key: 'type', name: 'type', title: this.i18n('boData.formType', '表单类型'), isField: true},
                {key: 'curUserId', name: 'curUserId', title: this.i18n('boData.curUserId', '用户ID'), isField: true},
                {
                    key: 'curUserName',
                    name: 'curUserName',
                    title: this.i18n('boData.curUserName', '用户名称'),
                    isField: true
                },
                {key: 'account', name: 'account', title: this.i18n('boData.account', '用户账号'), isField: true},
                {key: 'deptId', name: 'deptId', title: this.i18n('boData.deptId', '用户主部门ID'), isField: true},
                {key: 'instId', name: 'instId', title: this.i18n('boData.instId', '流程实例ID'), isField: true}],
            javaCode: '',
            validMsg: '',
            strOptions: [
                {value: 'EQ', label: this.i18n('strOptions.eq', '等于')},
                {value: 'NEQ', label: this.i18n('strOptions.noeq', '不等于')},
                {value: 'IN', label: this.i18n('strOptions.include', '包含')},
                {value: 'NIN', label: this.i18n('strOptions.notInclude', '不包含')},
                {value: 'ISNULL', label: this.i18n('strOptions.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('strOptions.notEmpty', '不为空')},
            ],
            numOptions: [
                {value: 'EQ', label: this.i18n('strOptions.eq', '等于')},
                {value: 'NEQ', label: this.i18n('strOptions.noeq', '不等于')},
                {value: 'LT', label: this.i18n('strOptions.under', '小于')},
                {value: 'LE', label: this.i18n('strOptions.leq', '小于等于')},
                {value: 'GT', label: this.i18n('strOptions.overtake', '大于')},
                {value: 'GE', label: this.i18n('strOptions.geq', '大于等于')},
                {value: 'ISNULL', label: this.i18n('strOptions.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('strOptions.notEmpty', '不为空')},
            ],
            dateOptions: [
                {value: 'EQ', label: this.i18n('strOptions.eq', '等于')},
                {value: 'LT', label: this.i18n('strOptions.under', '小于')},
                {value: 'GT', label: this.i18n('strOptions.overtake', '大于')},
                {value: 'ISNULL', label: this.i18n('strOptions.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('strOptions.notEmpty', '不为空')},
            ],
            search: ''
        }
    },
    created() {
        this.init();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoDef", key);
        },
        i18nSol(name, text, key) {
            return this.$ti18(name, text, "formSolution.buttonDef", key);
        },
        init() {
            if (this.config) {
                var json = JSON.parse(this.config);
                this.mode = json.mode;
                this.validMsg = json.validMsg;
                if (this.mode == 'easy') {
                    this.easyCondition = json.easyCondition;
                } else if (this.mode == 'hard') {
                    this.javaCode = json.javaCode;
                }
            }
            if (this.boDefId) {
                FormBoDefApi.getBoDefConstruct(this.boDefId, true, "").then(res => {
                    this.formFields = res.data.map(item => {
                        return {label: item.title, value: item.name, ...item};
                    })
                })
                FormBoDefApi.getBoDefConstruct(this.boDefId, false, "").then(res => {
                    this.boData.push({
                        key: 'formJson',
                        name: 'formJson',
                        title: this.i18n('easyColumns.formField', '表单字段'),
                        isField: false,
                        children: res.data
                    });
                    this.boDataInit = JSON.parse(JSON.stringify(this.boData));
                })
            }
        },
        handleSubmit(vm) {
            if(this.mode == 'easy'){
                let data = this.$refs.easyCondition.getData();
                //验证不通过 允许为空
                if(data.rules.length>0 && !data.valid){
                    vm.loading = false;
                    this.$message.warning("验证不通过！");
                    return "";
                }
            }
            Util.closeWindow(this, "ok", this.getData());
        },
        cancel() {
            Util.closeWindow(this, "cancel");
        },
        getData() {
            var obj = {mode: this.mode, validMsg: this.validMsg};
            if (this.mode == 'easy') {
                obj.easyCondition = this.$refs.easyCondition.getValue();
            } else if (this.mode == 'hard') {
                obj.javaCode = this.javaCode;
            }
            return JSON.stringify(obj);
        },
        formFieldChange(value, record,setValid) {
            if (!value) {
                setValid(record, false, this.i18nSol('fieldNoEmpty','字段不能为空'));
                return;
            } else {
                setValid(record, true);
            }
            for (var i = 0; i < this.formFields.length; i++) {
                if (value == this.formFields[i].value) {
                    record.dataType = this.formFields[i].dataType;
                    record.isSingle = this.formFields[i].isSingle;
                    if (record.isSingle === 0) {
                        this.$set(record, "fieldValue", "value");
                    } else {
                        record.fieldValue = "";
                    }
                    break;
                }
            }
            this.$set(record,"conditionConfig","");
            this.$set(record,"op",undefined);
        },
        showScriptDialog() {
            let self = this;
            let config = {curVm: this};
            Dialog.openScriptDialog(config, function (script) {
                self.$refs.javaCode.insertContent(script);
            })
        },
        selectBoNode(selKeys, e) {
            let node = e.node.dataRef;
            var isField = node.isField;
            var type = node.type;
            if (!isField) {
                return;
            }
            let parentNode = e.node.$parent.dataRef;
            if (!type || type == 'main') {
                this.insertJavaCode("formJson." + node.name);
            } else if (type == 'onetoone') {
                this.insertJavaCode("formJson.sub__" + node.entName + "." + node.name);
            } else if (type == 'onetomany') {
                this.insertJavaCode("formJson.sub__" + node.entName + "[0]." + node.name);
            }
        },
        selectBoNodeList(node) {
            this.insertJavaCode("context." + node.name);
        },
        //搜索
        pressEnter: _.debounce(function (e) {
            this.boData = JSON.parse(JSON.stringify(this.boDataInit));
            if (e) {
                this.boData[0].children = this.boData[0].children.filter(res => {
                    //子表
                    if (res.children) {
                        res.children = this.onetoone(res.children)
                        if (res.children.length > 0) {
                            return res;
                        }
                    } else {
                        return res.title.includes(this.search)
                    }
                })
            }
        }, 500),
        onetoone(list) {
            list = list.filter(item => {
                if (item.title.includes(this.search)) {
                    return true
                } else {
                    return false
                }
            })
            return list
        },
        insertJavaCode(text) {
            this.$refs.javaCode.insertContent(text);
        },
        change() {
            this.$forceUpdate()
        }
    }
}
</script>

<style scoped>
.form-tree-certen {
    position: relative;
}

.form-tree-certen:hover .form-tree {
    display: block;
}

.form-tree {
    position: absolute;
    top: 44px;
    display: none;
    left: 0px;
    min-width: 170px;
    max-height: 300px;
    overflow: auto;
    z-index: 1000;
    background-color: #ffffff;
    border-radius: 4px;
    border: solid 1px #e3e3e3;
}

.FormSolutionDefMappingConfig-easy {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.rx-monaco-editor-center {
    flex: 1;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
}

.formSolution {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
}

.addbutton {
    margin-bottom: 15px;
}

.formSolution-center {
    height: 100%;
    display: flex;
    flex: 1;
}

.formSolution-center-flex {
    flex-direction: column;
}

.findSelectBox {
    flex: 1;
    margin-right: 20px;
}

.findInputBox {
    flex: 2;
}
</style>